<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="queryParams.userId" placeholder="请输入奖励用户ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>


          <el-form-item prop="taskType">
            <el-select v-model="queryParams.taskType" placeholder="请输入活动奖励类型" clearable style="width: 240px">
              <el-option
                v-for="dict in tg_rewards_task_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <!-- 下拉框 -->
          <el-form-item label="用户标签">
            <el-select v-model="queryParams.taskUserTag" placeholder="请选择" clearable style="width: 240px">
              <el-option
                v-for="dict in data.taskTypeOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="日期" prop="taskDate">
            <el-date-picker v-model="queryParams.taskDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择" />
          </el-form-item>
          <el-form-item label="注册用户" prop="reUserId">
            <el-input v-model="queryParams.reUserId" placeholder="请输入注册用户ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userTaskRewards:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userTaskRewards:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userTaskRewards:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userTaskRewards:import']" type="success" plain icon="Top" @click="handleImport()">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userTaskRewards:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="userTaskRewardsList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="ID" align="center" prop="id" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="奖励用户ID" align="center" prop="userId" />
        <el-table-column label="姓名" align="center" prop="realName" />

        <el-table-column label="活动奖励类型" align="center" prop="taskType">
          <template #default="scope">
            <dict-tag :options="tg_rewards_task_type" :value="scope.row.taskType" />
          </template>
        </el-table-column>

        <el-table-column label="任务奖励" align="center" prop="taskRewards" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="奖励-ganme金币" align="center" prop="taskGold" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="奖励-ganme钻石" align="center" prop="taskDiamond" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="发放状态" align="center" prop="status" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="任务用户标签" align="center" prop="taskUserTag" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="奖励日期" align="center" prop="createTime" width="180" sortable="custom" :sort-orders="['ascending', 'descending']">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="注册用户" align="center" prop="reUserId" />
<!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['mushcoin:userTaskRewards:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['mushcoin:userTaskRewards:remove']"
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>-->
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改用户任务奖励列(H5)对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1000px" append-to-body>
      <el-form ref="userTaskRewardsFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动类型" prop="taskType">
              <el-input v-model="form.taskType" placeholder="请输入活动奖励类型" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="" prop="taskDate">
              <el-date-picker v-model="form.taskDate" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="注册用户" prop="reUserId">
              <el-input v-model="form.reUserId" placeholder="请输入注册用户" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import {
  listUserTaskRewards,
  getUserTaskRewards,
  delUserTaskRewards,
  addUserTaskRewards,
  updateUserTaskRewards
} from '@/api/mushcoin/userTaskRewards';
import { UserTaskRewardsVO, UserTaskRewardsQuery, UserTaskRewardsForm } from '@/api/mushcoin/userTaskRewards/types';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { tg_rewards_task_type } = toRefs<any>(proxy?.useDict('tg_rewards_task_type'));

// 表格数据
const userTaskRewardsList = ref<UserTaskRewardsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
// 选中数组
const ids = ref<Array<string | number>>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 总条数
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const userTaskRewardsFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();

/*** 导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 1,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/mushcoin/userTaskRewards/importData'
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: UserTaskRewardsForm = {
  id: undefined,
  userId: undefined,
  taskType: undefined,
  taskRewards: undefined,
  taskDate: undefined,
  reUserId: undefined
};
// 默认排序
const defaultSort = ref<any>({ prop: 'id', order: 'descending' });
const data = reactive<PageData<UserTaskRewardsForm, UserTaskRewardsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    userId: undefined,
    taskType: undefined,
    taskRewards: undefined,
    taskDate: undefined,
    reUserId: undefined,
    params: {},
    orderByColumn: defaultSort.value.prop,
    isAsc: defaultSort.value.order
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '奖励用户ID不能为空', trigger: 'blur' }],
    taskType: [{ required: true, message: '活动奖励类型不能为空', trigger: 'blur' }],
    taskRewards: [{ required: true, message: '任务奖励不能为空', trigger: 'blur' }],
    taskDate: [{ required: true, message: '不能为空', trigger: 'blur' }],
    reUserId: [{ required: true, message: '注册用户不能为空', trigger: 'blur' }]
  },
  taskTypeOptions: [
    { value: '0', label: '0' },
    { value: '3', label: '3' },
    { value: '10', label: '10' },
    { value: '30', label: '30' },
    { value: '50', label: '50' },
    { value: '80', label: '80' },
    { value: '100', label: '100' },
    { value: '200', label: '200' },
    { value: '300', label: '300' },
    { value: '500', label: '500' },
    { value: '800', label: '800' },
    { value: '1000', label: '1000' }
  ]
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户任务奖励列(H5)列表 */
const getList = async () => {
  loading.value = true;
  const res = await listUserTaskRewards(queryParams.value);
  userTaskRewardsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  userTaskRewardsFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserTaskRewardsVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 排序触发事件(my) */
/*const handleSortChange = ({ column, prop, order }) => {
  if (order === 'ascending') {
    queryParams.value.isAsc = 'asc';
  } else if (order === 'descending') {
    queryParams.value.isAsc = 'desc';
  }
  queryParams.value.orderByColumn = prop;
  queryParams.value.pageNum = 1; // 重置为第一页
  getList();
};*/

/** 排序触发事件(自带) */
const handleSortChange = (column: any) => {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = false;
  dialog.title = '添加用户任务奖励列(H5)';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: UserTaskRewardsVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getUserTaskRewards(_id);
  Object.assign(form.value, res.data);
  dialog.visible = false;
  dialog.title = '修改用户任务奖励列(H5)';
};

/** 提交按钮 */
const submitForm = () => {
  userTaskRewardsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateUserTaskRewards(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addUserTaskRewards(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: UserTaskRewardsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除用户任务奖励列(H5)编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delUserTaskRewards(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'mushcoin/userTaskRewards/export',
    {
      ...queryParams.value
    },
    `userTaskRewards_${new Date().getTime()}.xlsx`
  );
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '用户任务奖励列(H5)导入';
  upload.open = true;
};

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('mushcoin/userTaskRewards/importTemplate', {}, `userTaskRewards_template.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

onMounted(() => {
  getList();
});
</script>
